package com.yanqu.road.web.mgr;

import com.yanqu.road.entity.statistics.RoleStatistics;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.statistics.RoleStatisticsBusiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.AutoOpenServerMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.player.PlayerInfoChangeNotifyMgr;
import com.yanqu.road.server.manger.player.task.PlayInfoChangeType;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.web.WebServer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class UserIdMgr extends TempMgr {

    private static AtomicLong maxUserId;

    private static Map<String, Object> registerLockerMap;

    private static RoleStatistics preRoleStatistics;
    private static RoleStatistics nowRoleStatistics;
    //创角人数
    private static long totalRoleCreateCount;
    //有效创角
    private static long totalRoleCreateCount2;
    private static Object statisticsLock = new Object();

    public synchronized static Object getOpenIdLocker(String openId) {
        if (registerLockerMap == null) {
            registerLockerMap = new ConcurrentHashMap<>();
        }

        if (!registerLockerMap.containsKey(openId)) {
            registerLockerMap.put(openId, new Object());
        }

        return registerLockerMap.get(openId);
    }

    @Override
    public boolean save() {
        if(null != preRoleStatistics){
            if(preRoleStatistics.isInsertOption()){
                RoleStatisticsBusiness.addRoleStatistics(preRoleStatistics);
            }else if(preRoleStatistics.isUpdateOption()){
                RoleStatisticsBusiness.updateRoleStatistics(preRoleStatistics);
            }
        }
        if(null != nowRoleStatistics){
            if(nowRoleStatistics.isInsertOption()){
                RoleStatisticsBusiness.addRoleStatistics(nowRoleStatistics);
            }else if(nowRoleStatistics.isUpdateOption()){
                RoleStatisticsBusiness.updateRoleStatistics(nowRoleStatistics);
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public boolean init() throws Exception {
        PlayerInfoChangeNotifyMgr.addSyncListener(PlayInfoChangeType.Title.getType(), (eventType, userId, args) -> {
            int title = (int)args.getArgs();
            int channelId = ServerListMgr.getChannelId(WebServer.getInstance().getServerId());
            if(title == AutoOpenServerMgr.getAutoOpenRoleLevel(channelId)){
                //有效创角色+1
                addRoleCreateCount2(1);
            }
        });
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    public boolean reloadData() {
        long tempMaxUserId1 = UserBussiness.getMaxUserId();
        long tempMaxUserId2 = UserBussiness.getMaxUserIdPre();
        long tempMaxUserId = Math.max(tempMaxUserId1,tempMaxUserId2);
        if (0 == tempMaxUserId) {
            String serverId = String.valueOf(WebServer.getInstance().getServerId());
            //玩家编号15位
            while (serverId.length() < 15) {
                serverId += 0;
            }
            maxUserId = new AtomicLong(Long.valueOf(serverId));
        } else {
            maxUserId = new AtomicLong(tempMaxUserId);
        }
        RoleStatistics temp = RoleStatisticsBusiness.getRoleStatistics();
        synchronized (statisticsLock){
            long nowTime = System.currentTimeMillis();
            long hoursTimeStamp = DateHelper.getHoursTimeStamp(nowTime);
            if(null == temp || temp.getHoursTimeStamp() != hoursTimeStamp){
                getCurRoleStatistics();
            }else {
                nowRoleStatistics = temp;
            }
        }
        totalRoleCreateCount = UserBussiness.getRoleCreateCount();
        int channelId = ServerListMgr.getChannelId(WebServer.getInstance().getServerId());
        totalRoleCreateCount2 = UserBussiness.getRoleCreateCount2(AutoOpenServerMgr.getAutoOpenRoleLevel(channelId));
        return true;
    }

    public static RoleStatistics getCurRoleStatistics(){
        synchronized (statisticsLock){
            long hoursTimeStamp = DateHelper.getHoursTimeStamp();
            if(null == nowRoleStatistics){
                RoleStatistics data = new RoleStatistics();
                data.setHoursTimeStamp(hoursTimeStamp);
                data.setInsertOption();
                nowRoleStatistics = data;
            }else {
                if(nowRoleStatistics.getHoursTimeStamp() != hoursTimeStamp){
                    preRoleStatistics = nowRoleStatistics;
                    RoleStatistics data = new RoleStatistics();
                    data.setHoursTimeStamp(hoursTimeStamp);
                    data.setInsertOption();
                    nowRoleStatistics = data;
                }
            }
        }
        return nowRoleStatistics;
    }

    public static long getNextUserId() {
        return maxUserId.incrementAndGet();
    }

    /**
    * 描述：生成短用户编号，超过1000个服不适用，已废弃
    * 作者：zrq
    * 时间：2022/8/10
    * 参数：
    玩家编号
    * 返回值：
    **/
//    public static long getUserAliasId(long userId) {
//        // ShareMgr.getUserIdByAliasId有用到这里的转换逻辑和上面maxUserId生成逻辑
//        String userIdStr = String.valueOf(userId);
//        String userAliasIdStr = userIdStr.substring(5);
//        userAliasIdStr = "1" + userAliasIdStr;
//        return Long.parseLong(userAliasIdStr);
//    }

    public static long getUserAliasId(long userId) {
        // ShareMgr.getUserIdByAliasId有用到这里的转换逻辑和上面maxUserId生成逻辑
        String userIdStr = String.valueOf(userId);
        String markStr = userIdStr.substring(3, 5);
        int mark = Integer.parseInt(markStr);
        String userAliasIdStr = userIdStr.substring(5);
        userAliasIdStr = "" + (mark + 1) + userAliasIdStr;
        return Long.parseLong(userAliasIdStr);
    }

    public static long getTotalRoleCreateCount() {
        return totalRoleCreateCount;
    }

    public static long getTotalRoleCreateCount2() {
        return totalRoleCreateCount2;
    }

    public static void addRoleCreateCount(long count){
        synchronized (statisticsLock){
            RoleStatistics data = getCurRoleStatistics();
            data.setCreateRoleCount(data.getCreateRoleCount() + count);
            totalRoleCreateCount++;
        }
    }

    public static void addRoleCreateCount2(long count){
        synchronized (statisticsLock){
            RoleStatistics data = getCurRoleStatistics();
            data.setCreateRoleCount2(data.getCreateRoleCount2() + count);
            totalRoleCreateCount2++;
        }
    }

    public static void addRegisterCount(long count){
        synchronized (statisticsLock){
            RoleStatistics data = getCurRoleStatistics();
            data.setRegisterCount(data.getRegisterCount() + count);
        }
    }

    public static void main(String[] args) {
//        int end = 20199999;
        int start = 20100998;
        int end = 20101001;
        for(int i = start; i <= end; i++) {
            String uStr = "" + i + "0000001";
            long userId = Long.parseLong(uStr);
            long aliasId = getUserAliasId(userId);
            System.out.println("aliasId:" + aliasId);
            System.out.println("userId:" + userId);
        }
    }
}
